package com.levy.web;

import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.levy.domain.User;
import com.levy.service.UserService;

/**
 * 登录控制器
 *
 * @author liwei515
 */
@Controller  // 标注成为一个Spring MVC的Controller，也是Bean，处理HTTP请求
public class LoginController {

  private UserService userService;

  /**
   * set方法注入UserService用户业务服务
   *
   * @param userService 用户业务服务
   */
  public void setUserService(UserService userService) {
    this.userService = userService;
  }

  /**
   * 负责处理/index.html的请求
   *
   * @return login
   */
  @RequestMapping(value = "/index.html")
  public String loginPage() {
    return "login";
  }

  /**
   * 负责处理/loginCheck.html的请求
   *
   * @param request 请求
   * @param loginCommand 登录需求
   * @return ModelAndView
   */
  @RequestMapping("/loginCheck.html")
  public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand) {
    boolean isValidUser = userService.hasMatchUser(loginCommand.getUserName(), loginCommand.getPassword());
    if (!isValidUser) {
      return new ModelAndView("login", "error", "用户名或密码错误！");
    } else {
      User user = userService.findUserByUserName(loginCommand.getUserName());
      user.setLastVisit(new Date());
      user.setLastIp(request.getLocalAddr());
      userService.loginSuccess(user);
      request.getSession().setAttribute("user", user);
      return new ModelAndView("main");
    }
  }

}
